package MyPackage;
import java.util.*;
import java.io.*;
public class Main {

	public static void main(String[] args) {
		
System.out.println("MyCMD start...");
Scanner inp=new Scanner(System.in);

	String dir;
	String mask;
	dir="D:\\doc\\del";
	mask="ab*w*.t*";
	
	System.out.println("\nExercise 3\n**Search in a directory**\nInput directory:");
	dir=inp.nextLine();
	System.out.println("Input mask:\nExample: ab*w*.t*t");
	mask=inp.nextLine();
	System.out.println("===Search: "+mask+"===");
	searchInTree(dir,mask);
		
System.out.println("\nMyCMD stop.");
	}
	
	public static void searchInTree(String dir, String mask){
		//Method runs searchInDir only in folder - 'dir' and run itself in all include folders
		File f=new File(dir);
		if(!f.exists()) System.out.println("Not found directory "+f.toString());
		else{
	
		searchInDir(dir,mask);
		String[] dirList=f.list();
		for(int i=0;i<dirList.length;i++){
			String absDir=dir+File.separator+dirList[i];
			File f1=new File(absDir);
			if(!f1.isFile()) searchInTree(absDir,mask);
			}
		}
	}		

	public static void searchInDir(String dir, String mask){
		File f=new File(dir);
		if(!f.exists()) System.out.println("Not found directory "+f.toString());
		else{
		
		
		String[] dirList=f.list();
		String[] arrayMask;
		
		if(mask.contains("*")) mask=mask.replace("*", "`");
		
		if(mask.contains("`")){
				arrayMask = mask.split("`");
		
		for(int i=0;i<dirList.length;i++) {
			String sDirList=dirList[i];
			int k=0;
			while(sDirList.length()>0 && k<arrayMask.length){
				if(sDirList.startsWith(arrayMask[k])){
					for(int r=0; r<arrayMask[k].length();r++) sDirList=cutDir(sDirList);
					k++;
				}
				else{ 
					sDirList=cutDir(sDirList);
				}
			}
			if(k>=arrayMask.length)	printName(dir+File.separator+dirList[i]);
		}
		
		}
		else{
			for(int i=0;i<dirList.length;i++) {
				if(dirList[i].equals(mask))	printName(dir+File.separator+dirList[i]);
			}
		}
		
		}
	}
		
	public static void printName(String dirName){
		File f1=new File(dirName);
		Date date=new Date(f1.lastModified());
		System.out.println(f1.getName()+" \t"+date+" "+f1.getPath());
	} 
	
	public static String cutDir(String dir){
			int ld=dir.length();
			char[] newDir=new char[ld-1];
			dir.getChars(1, ld, newDir, 0);
			String sNewDir=newDir.toString();
			sNewDir=sNewDir.copyValueOf(newDir);
	return sNewDir;
	}
}	




